package mi.payment.ui.view;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import mi.payment.R;
import mi.payment.interfaces.DefaultTextWatcher;


public class CleanableEditText extends EditText {
    private Drawable[] drawables;
    private Drawable imgClean;

    public CleanableEditText(Context context) {
        super(context);
        initView();
    }

    public CleanableEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    public CleanableEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    private void initView() {
        imgClean = getContext().getResources().getDrawable(R.drawable.ic_clean);
        drawables = getCompoundDrawables();
        addTextChangedListener(new DefaultTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                setCleanButtonEnable(s.length() > 0);
            }
        });

        setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                setCleanButtonEnable(hasFocus && getText().length() > 0);
            }
        });
    }

    private void setCleanButtonEnable(boolean enable) {
        if (enable) {
            setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], imgClean, drawables[3]);
        } else {
            setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], null, drawables[3]);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (imgClean != null && event.getAction() == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            // 判断触摸点是否在水平范围内
            boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight()))
                    && (x < (getWidth() - getPaddingRight()));
            // 获取删除图标的边界，返回一个Rect对象
            Rect rect = imgClean.getBounds();
            // 获取删除图标的高度
            int height = rect.height();
            // 计算图标底部到控件底部的距离
            int distance = (getHeight() - height) / 2;
            // 判断触摸点是否在竖直范围内(可能会有点误差)
            // 触摸点的纵坐标在distance到（distance+图标自身的高度）之内，则视为点中删除图标
            boolean isInnerHeight = (y > distance) && (y < (distance + height));

            if (isInnerWidth && isInnerHeight) {
                setText("");
            }
        }
        return super.onTouchEvent(event);
    }
}
